package com.chucang.shucang.usr.listener;

import com.chucang.shucang.common.base.constant.CommonConstant;
import com.chucang.shucang.common.base.exception.FastException;
import com.chucang.shucang.common.base.utils.OpsUtil;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.mq.constant.RabbitConstant;
import com.chucang.shucang.usr.constant.UsrCommonConstant;
import com.chucang.shucang.usr.feign.OmsService;
import com.chucang.shucang.usr.feign.vo.*;
import com.chucang.shucang.usr.service.UserWalletService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/23 18:07
 * @description 阿里藏品支付
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RabbitListener(queues = RabbitConstant.ALIPAY_COLLECTION_SUCCESS_QUEUE)
public class CollectionOrderSuccessListener {

    private final UserWalletService userWalletService;
    private final OmsService omsService;

    @RabbitHandler
    public void collectionOrderListener(String orderSn, Channel channel, Message message) throws IOException {
        log.info("获取到藏品支付成功信息！");
        try {
            //处理藏品订单
            R<CollectionOrderBaseResVO> orderBaseResVOR = omsService.checkCollectionOrder(orderSn);
            CollectionOrderBaseResVO orderBaseResVO = OpsUtil.of(orderBaseResVOR)
                    .assertCode(CommonConstant.SUCCESS, e -> new FastException("获取订单信息异常！"))
                    .getData()
                    .get();
            userWalletService.collectionOrderSuccess(orderBaseResVO, UsrCommonConstant.FROM_WALLET);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("藏品支付处理异常！");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
